package com.beeantec.jnrerc.modules.member.controller;



import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.beeantec.jnrerc.core.annon.LogInject;
import com.beeantec.jnrerc.core.api.ApiRest;
import com.beeantec.jnrerc.core.api.controller.BaseController;
import com.beeantec.jnrerc.core.utils.RedisUtils;
import com.beeantec.jnrerc.dto.MemberVo;
import com.beeantec.jnrerc.dto.request.*;
import com.beeantec.jnrerc.dto.response.*;
import com.beeantec.jnrerc.entity.*;
import com.beeantec.jnrerc.modules.course.service.CourseMemberStudyLogService;
import com.beeantec.jnrerc.modules.course.service.CourseMemberStudyService;
import com.beeantec.jnrerc.modules.course.service.CourseService;
import com.beeantec.jnrerc.modules.member.service.GrowRecordService;
import com.beeantec.jnrerc.modules.member.service.MemberLoginService;
import com.beeantec.jnrerc.modules.member.service.MemberService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;


@Api(tags={"用户"})
@RestController
@RequestMapping("/api/member")
public class MemberController extends BaseController {


    @Autowired
    RedisUtils redisUtils;

    @Autowired
    MemberService memberService;

    @Autowired
    MemberLoginService memberLoginService;


    @Autowired
    CourseMemberStudyLogService courseMemberStudyLogService;


    @Autowired
    CourseMemberStudyService courseMemberStudyService;

    @Autowired
    CourseService courseService;


    @Autowired
    GrowRecordService growRecordService;

    /**
     * 用户登录
     * @return
     */
    @LogInject(title = "App登录")
    @CrossOrigin
    @ApiOperation(value = "用户登录")
    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public ApiRest<MemberVo> login(@RequestBody LoginReqDTO loginReqDTO) {
        MemberVo memberVo = memberLoginService.login(loginReqDTO.getLoginType(), loginReqDTO.getId(),loginReqDTO.getPhone(),loginReqDTO.getSms());
        if (null==memberVo){
            return super.failure("验证码校验失败");
        }
        return super.success(memberVo);
    }


    /**
     * 用户登录
     * @return
     */
    @LogInject(title = "微信绑定手机号")
    @CrossOrigin
    @ApiOperation(value = "微信绑定手机号")
    @RequestMapping(value = "/bindPhone", method = {RequestMethod.POST})
    public ApiRest<BindRespDTO> bindPhone(@RequestBody BindReqDTO bindReqDTO) {
        BindRespDTO bindRespDTO = memberService.wxBindPhone( bindReqDTO.getId(),bindReqDTO.getPhone(),bindReqDTO.getSms());
        return super.success(bindRespDTO);
    }

    /**
     * 用户登录
     * @return
     */
    @LogInject(title = "手机号绑定微信号")
    @CrossOrigin
    @ApiOperation(value = "微信绑定手机号")
    @RequestMapping(value = "/bindWechat", method = {RequestMethod.POST})
    public ApiRest<BindRespDTO> bindWechat(@RequestBody BindReqDTO bindReqDTO) {
        BindRespDTO bindRespDTO = memberService.bindWechat( bindReqDTO.getId(),bindReqDTO.getPhone());
        return super.success(bindRespDTO);
    }



    /**
     * 用户登录
     * @return
     */
    @LogInject(title = "根据Id获取用户信息")
    @CrossOrigin
    @ApiOperation(value = "根据Id获取用户信息")
    @RequestMapping(value = "/getMemberInfoById", method = {RequestMethod.POST})
    public ApiRest<MemberVo> getMemberInfo(@RequestBody MemberInfoReqDTO memberInfoReqDTO) {
        MemberVo memberVo = new MemberVo();
        BeanUtils.copyProperties( memberService.getById( memberInfoReqDTO.getMemberId()),memberVo);
        return super.success(memberVo);
    }

    /**
     * 用户登录
     * @return
     */
    @LogInject(title = "根据Id获取用户信息")
    @CrossOrigin
    @ApiOperation(value = "根据Id获取用户信息")
    @RequestMapping(value = "/getMemberInfoByPhone", method = {RequestMethod.POST})
    public ApiRest<MemberVo> getMemberInfoByPhone(@RequestBody MemberInfoReqDTO memberInfoReqDTO) {
        return super.success(memberService.getByPhone( memberInfoReqDTO.getMemberId()));
    }


    /**
     * 获取会话
     * @return
     */
    @ApiOperation(value = "获取登录用户信息")
    @RequestMapping(value = "/info", method = {RequestMethod.POST})
    public ApiRest<MemberVo> info(@RequestHeader("token") String token) {
        MemberVo memberVo = memberService.token(token);
        return success(memberVo);
    }


    /**
     * 获取我的课程列表
     * @return
     */
    @ApiOperation(value = "获取我的课程列表")
    @RequestMapping(value = "/courseList", method = {RequestMethod.GET})
    public ApiRest<List<MemberCourseRespDTO>> courseList(@RequestHeader("token") String token) {
        List<MemberCourseRespDTO> respDTOList = new ArrayList<>();
        MemberVo memberVo = memberService.token(token);
        QueryWrapper<CourseMemberStudy> courseMemberStudyQueryWrapper = new QueryWrapper<>();
        courseMemberStudyQueryWrapper.lambda().eq(CourseMemberStudy::getMemberId,memberVo.getMemberId());
        List<CourseMemberStudy> courseMemberStudies = courseMemberStudyService.getBaseMapper().selectList(courseMemberStudyQueryWrapper);
        if (null== courseMemberStudies||courseMemberStudies.isEmpty()){
            return success(respDTOList);
        }
        for (CourseMemberStudy courseMemberStudy:courseMemberStudies){
            MemberCourseRespDTO groupMemberRespDTO = new MemberCourseRespDTO();

            //获取用户已学节数
            QueryWrapper<CourseMemberStudyLog> logQueryWrapper = new QueryWrapper<>();
            logQueryWrapper.lambda().eq(CourseMemberStudyLog::getMemberId,memberVo.getMemberId())
                    .eq(CourseMemberStudyLog::getCourseId,courseMemberStudy.getCourseId());
            //计算课程总节数
            int studyCount = courseMemberStudyLogService.getBaseMapper().selectList(logQueryWrapper).size();
            double progress = (double) studyCount/courseMemberStudy.getPeriodTotal();
            Course course = courseService.getById(courseMemberStudy.getCourseId());
            groupMemberRespDTO.setCourseProgress(progress);
            groupMemberRespDTO.setCourseId(course.getId());
            groupMemberRespDTO.setCourseName(course.getCourseName());
            groupMemberRespDTO.setCourseIcon(course.getCourseLogo());
            respDTOList.add(groupMemberRespDTO);
        }
        return success(respDTOList);
    }


    private int getUserStudyCount(String token,Long courseId){
        MemberVo memberVo = memberService.token(token);
        //获取用户已学节数
        QueryWrapper<CourseMemberStudyLog> logQueryWrapper = new QueryWrapper<>();
        logQueryWrapper.lambda().eq(CourseMemberStudyLog::getMemberId,memberVo.getMemberId())
                .eq(CourseMemberStudyLog::getCourseId,courseId);
        //计算课程总节数
        return courseMemberStudyLogService.getBaseMapper().selectList(logQueryWrapper).size();

    }



    /**
     * 用户课程详情接口
     *
     * @return
     */
    @ApiOperation(value = "用户课程详情接口", notes = "用户课程详情接口")
    @RequestMapping(value = "/courseInfo", method = RequestMethod.GET)
    public ApiRest<MemberCourseDetailRespDTO> info(@RequestHeader("token") String token,@RequestParam("courseId") Long courseId) {
        MemberCourseDetailRespDTO memberCourseDetailRespDTO = new MemberCourseDetailRespDTO();
        CourseReqDTO courseReqDTO = new CourseReqDTO();
        courseReqDTO.setCourseId(courseId);
        CourseInfoDTO courseInfoDTO =courseService.info(token,courseId);
        memberCourseDetailRespDTO.setCourseInfoDTO(courseInfoDTO);
        int studyCount = getUserStudyCount(token,courseId);
        double progress = (double) studyCount/courseInfoDTO.getPeriodTotal();
        memberCourseDetailRespDTO.setProgress(progress);
        return success(memberCourseDetailRespDTO);
    }


    /**
     * 用户学习课程
     * @return
     */
    @ApiOperation(value = "用户学习课程")
    @RequestMapping(value = "/learnCourse", method = {RequestMethod.GET})
    public ApiRest<Boolean> learnCourse(@RequestHeader("token") String token,@RequestParam("courseId") String courseId) {
        MemberVo memberVo = memberService.token(token);
        QueryWrapper<CourseMemberStudy> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(CourseMemberStudy::getMemberId,memberVo.getMemberId())
        .eq(CourseMemberStudy::getCourseId,Long.parseLong(courseId));
        Course course = courseService.getById(Long.parseLong(courseId));
        CourseMemberStudy courseMemberStudy =courseMemberStudyService.getOne(queryWrapper);
        if (null==courseMemberStudy){
            courseMemberStudy = new CourseMemberStudy();
            courseMemberStudy.setCourseId(Long.parseLong(courseId));
            courseMemberStudy.setMemberId(memberVo.getMemberId());
            courseMemberStudy.setPeriodStudy(0);
            courseMemberStudy.setPeriodTotal(course.getPeriodTotal());
            courseMemberStudy.setStatusId(1);
            courseMemberStudy.setSort(1);
           boolean result =  courseMemberStudyService.save(courseMemberStudy);
           return success(result);
        }
        return success(true);
    }








    /**
     * 用户登录
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "用户退出登录")
    @RequestMapping(value = "/logout", method = {RequestMethod.POST})
    public ApiRest logout(HttpServletRequest request) {
        String token = request.getHeader("token");
        System.out.println("+++++当前会话为："+token);
        memberLoginService.logout(token);
        return super.success();
    }


    /**
     * 用户登录
     * @return
     */
    @LogInject(title = "更新用户信息")
    @CrossOrigin
    @ApiOperation(value = "更新用户信息")
    @RequestMapping(value = "/updateMemberInfo", method = {RequestMethod.POST})
    public ApiRest<Boolean> updateMemberInfo(@RequestHeader String token,@RequestBody MemberUpdateReqDTO memberUpdateReqDTO) {
        MemberVo memberVo = memberService.token(token);

        Member member =memberService.getById(memberVo.getMemberId());
        member.setAvatarUrl(memberUpdateReqDTO.getHead());
        member.setGender(memberUpdateReqDTO.getGender());
        member.setNickName(memberUpdateReqDTO.getNickName());
        return super.success(memberService.saveOrUpdate(member));
    }



    /**
     * 用户登录
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "用户成长记录")
    @RequestMapping(value = "/growrecord", method = {RequestMethod.GET})
    public ApiRest<List<GrowRecord>> growList(@RequestHeader("token") String token,@RequestParam("type") Integer type) {
        MemberVo memberVo = memberService.token(token);
        List<GrowRecord> growRecordList = new ArrayList<>();
        QueryWrapper<GrowRecord> growRecordQueryWrapper = new QueryWrapper<>();
        growRecordQueryWrapper.lambda().eq(GrowRecord::getMemberId,memberVo.getMemberId())
                .eq(GrowRecord::getType,type).orderByDesc(GrowRecord::getCreateTime);
        growRecordList = growRecordService.list(growRecordQueryWrapper);
        return super.success(growRecordList);
    }



    /**
     * 根据部门获取用户列表
     * @return
     */
    @CrossOrigin
    @ApiOperation(value = "根据部门获取用户列表")
    @RequestMapping(value = "/memberList", method = {RequestMethod.GET})
    public ApiRest<List<Member>> getMemberListByDepId(@RequestHeader("token") String token,@RequestParam("depId") Integer depId) {
        MemberVo memberVo = memberService.token(token);
        List<Member> memberList = new ArrayList<>();
        QueryWrapper<Member> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Member::getDepId,depId).ne(Member::getMemberId,memberVo.getMemberId()).ne(Member::getMemberId,0);
        memberList = memberService.list(queryWrapper);
        return super.success(memberList);
    }



}
